import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  SafeAreaView,
  ScrollView,
  StatusBar,
  Alert,
} from 'react-native';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import Icon from 'react-native-vector-icons/FontAwesome';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function CartScreen({ route }) {
  // 1. 用useState定义购物车数组
  const [cartItems, setCartItems] = useState(route?.params?.cartItems || []);
  console.log(cartItems)
  // 2. 计算总价
  const total = cartItems.reduce(
    (sum, item) => sum + item.price * item.quantity,
    0
  );
  const images = {
    '../assets/1.jpg': require('../assets/1.jpg'),
    '../assets/2.jpg': require('../assets/2.jpg'),
    '../assets/3.jpg': require('../assets/3.jpg'),
    '../assets/4.jpg': require('../assets/4.jpg'),
    '../assets/5.jpg': require('../assets/5.jpg'),
    '../assets/6.jpg': require('../assets/6.jpg'),
    '../assets/7.jpg': require('../assets/7.jpg'),
    '../assets/8.jpg': require('../assets/8.jpg'),
  }

  const navigation = useNavigation();

  const handleCheckout = async () => {
    if (!total || parseFloat(total) <= 0) {
      Alert.alert('错误', '请输入有效金额');
      return;
    }

    try {
      // 获取当前余额
      const currentMoneyStr = await AsyncStorage.getItem('money');
      const currentMoney = parseFloat(currentMoneyStr) || 0;

      if (currentMoney < total) {
        Alert.alert('余额不足', '您的余额不足，请先充值');
        return;
      }

      // 请求后端
      const response = await fetch('http://192.168.78.1:3000/pay/alipay', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ amount: parseFloat(total), merchant: cartItems[0].merchant }),
      });
      const result = await response.json();

      if (result.code === 200) {
        // 结算成功后，扣减金额
        const newMoney = (currentMoney - parseFloat(total)).toString();
        await AsyncStorage.setItem('money', newMoney);
        // 跳转到支付页面
        navigation.navigate('AlipayWebView', { html: result.data });
      } else {
        Alert.alert('错误', '创建支付订单失败');
      }
    } catch (error) {
      console.error('支付请求失败:', error);
      Alert.alert('错误', '支付请求失败');
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar backgroundColor="#fff" barStyle="dark-content" />
      {/* 顶部栏 */}
      <View style={styles.header}>
        <Text style={styles.headerTitle}>购物车</Text>
        <TouchableOpacity>
          <Icon name="cog" size={wp(6)} color="#fff" />
        </TouchableOpacity>
      </View>

      {/* 3. 判断cartItems数组是否为空 */}
      {cartItems.length === 0 ? (
        <View style={styles.emptyBox}>
          <Text style={styles.emptyText}>快去添加商品吧~</Text>
        </View>
      ) : (
        <ScrollView style={{ flex: 1 }}>
          <View style={styles.shopBox}>
            <View style={styles.shopHeader}>
              <Icon name="shopping-bag" size={wp(5)} color="#E71B24" style={{ marginRight: wp(2) }} />
              <Text style={styles.shopName}>子墨无敌店</Text>
            </View>
            {cartItems.map((item, i) => (
              <View key={item.id} style={styles.productBox}>
                <Image source={images[item.image]} style={styles.productImage} />
                <View style={styles.productInfo}>
                  <Text style={styles.productTitle} numberOfLines={2}>{item.title}</Text>
                  <Text style={styles.productDesc}>{item.desc}</Text>
                  <Text style={styles.productPrice}>￥{item.price.toFixed(2)}</Text>
                </View>
                <View style={styles.quantityBox}>
                  <TouchableOpacity style={styles.qtyBtn}><Text style={styles.qtyBtnText}>-</Text></TouchableOpacity>
                  <Text style={styles.qtyText}>{item.quantity}</Text>
                  <TouchableOpacity style={styles.qtyBtn}><Text style={styles.qtyBtnText}>+</Text></TouchableOpacity>
                </View>
              </View>
            ))}
          </View>
        </ScrollView>
      )}

      {/* 底部结算栏 */}
      <View style={styles.bottomBar}>
        <View style={styles.bottomLeft}>
          <Text style={styles.totalText}>合计：</Text>
          <Text style={styles.totalPrice}>￥{total.toFixed(2)}</Text>
        </View>
        <TouchableOpacity style={styles.checkoutBtn} onPress={handleCheckout}>
          <Text style={styles.checkoutText}>结算</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#f5f5f5' },
  header: {
    backgroundColor: '#E71B24',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: wp(4),
    paddingVertical: hp(1.5),
  },
  headerTitle: {
    color: '#fff',
    fontSize: wp(4.5),
    fontWeight: 'bold',
  },
  headerIcon: {
    width: wp(6),
    height: wp(6),
    tintColor: '#fff',
  },
  shopBox: {
    backgroundColor: '#fff',
    borderRadius: wp(2),
    marginHorizontal: wp(2),
    marginTop: hp(2),
    paddingBottom: hp(1),
    shadowColor: '#000',
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  shopHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: wp(3),
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  shopIcon: {
    width: wp(5),
    height: wp(5),
    marginRight: wp(2),
  },
  shopName: {
    fontSize: wp(3.8),
    color: '#333',
    fontWeight: 'bold',
  },
  productBox: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: wp(3),
    borderBottomWidth: 1,
    borderBottomColor: '#f5f5f5',
  },
  productImage: {
    width: wp(16),
    height: wp(16),
    borderRadius: wp(2),
    marginRight: wp(3),
  },
  productInfo: {
    flex: 1,
    justifyContent: 'space-between',
  },
  productTitle: {
    fontSize: wp(3.5),
    color: '#222',
    fontWeight: 'bold',
    marginBottom: hp(0.5),
  },
  productDesc: {
    fontSize: wp(2.8),
    color: '#888',
    marginBottom: hp(0.5),
  },
  productPrice: {
    color: '#E71B24',
    fontSize: wp(4),
    fontWeight: 'bold',
  },
  quantityBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: wp(2),
  },
  qtyBtn: {
    width: wp(6),
    height: wp(6),
    borderRadius: wp(1),
    backgroundColor: '#f0f0f0',
    alignItems: 'center',
    justifyContent: 'center',
  },
  qtyBtnText: {
    fontSize: wp(4),
    color: '#333',
  },
  qtyText: {
    width: wp(6),
    textAlign: 'center',
    fontSize: wp(3.5),
    color: '#333',
  },
  bottomBar: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#fff',
    paddingVertical: hp(1.5),
    paddingHorizontal: wp(4),
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  bottomLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  totalText: {
    fontSize: wp(3.5),
    color: '#333',
  },
  totalPrice: {
    fontSize: wp(4),
    color: '#E71B24',
    fontWeight: 'bold',
    marginLeft: wp(1),
  },
  checkoutBtn: {
    backgroundColor: '#E71B24',
    borderRadius: wp(2),
    paddingVertical: hp(1),
    paddingHorizontal: wp(6),
  },
  checkoutText: {
    color: '#fff',
    fontSize: wp(4),
    fontWeight: 'bold',
  },
  emptyBox: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  emptyText: {
    color: '#999',
    fontSize: wp(4),
    marginTop: hp(10),
  },
}); 